package golf.stockdata.framework.util.hbm;

import java.math.BigInteger;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.type.StandardBasicTypes;

public class IdGenerator {
	
	private static Long ID_CACHE = null;
	private static long NEXT_LIMIT = 0;
	private static long GENERATOR_INTERVAL = 100;
	
	private static Logger logger = Logger.getLogger(IdGenerator.class);
	
	public static synchronized long getNext(){
		
		logger.debug(">>> getNext");
		
		if(ID_CACHE == null
				|| ID_CACHE >= NEXT_LIMIT){
			
			logger.debug("Either null or hit limit, to get next value from DB");
			
			ID_CACHE = getNextFromDB();
			NEXT_LIMIT = ID_CACHE + GENERATOR_INTERVAL;
		}
		
		logger.debug("<<< getNext");
		return ID_CACHE++;
		
	}
	
	private static long getNextFromDB(){
		
		logger.debug(">>> getNextFromDB");
		Query query = HibernateUtil.createHibernatesession().createSQLQuery("select GENERAL_ID_SEQ.nextval as num from dual").addScalar("num", StandardBasicTypes.BIG_INTEGER);
		logger.debug("<<< getNextFromDB");
		return ((BigInteger) query.uniqueResult()).longValue();
	}

}
